package com.example.es.util;

import com.example.es.entity.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 批量操作文档
 * @author: ruoan
 * @date: 2020/10/11 11:57
 */
public class EsRestHighLevelClientTest4 {

    private RestHighLevelClient client= EsRestHighLevelClient.getClient();
    private final String index = "person";
    private final String type = "_doc";  //es默认type=_doc


    /**
     * 批量操作文档
     */
    @Test
    public void bulkCreateDoc() throws IOException {
        Person p = new Person(1,"张三",18,new Date());
        Person p2 = new Person(2,"李四",28,new Date());
        Person p3 = new Person(3,"王五",38,new Date());
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonP = objectMapper.writeValueAsString(p);
        String jsonP2 = objectMapper.writeValueAsString(p2);
        String jsonP3 = objectMapper.writeValueAsString(p3);

        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.add(new IndexRequest(index, type, p.getId().toString()).source(jsonP,XContentType.JSON));
        bulkRequest.add(new IndexRequest(index, type, p2.getId().toString()).source(jsonP2,XContentType.JSON));
        bulkRequest.add(new IndexRequest(index, type, p3.getId().toString()).source(jsonP3,XContentType.JSON));

        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.toString());

    }





    /**
     * 批量删除文档
     */
    @Test
    public void bulkDeleteDoc() throws IOException {


        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.add(new DeleteRequest(index, type, "1"));
        bulkRequest.add(new DeleteRequest(index, type, "2"));
        bulkRequest.add(new DeleteRequest(index, type, "3"));

        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.toString());

    }




}